package vn.qnamuni.calendar.alarm;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Set;

import vn.qnamuni.calendar.constants.PersonContract;
import vn.qnamuni.calendar.providers.MyContentProvider;
import vn.qnamuni.calendar.reciever.AlarmReciever;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.util.Log;
import android.util.SparseArray;
import android.widget.Toast;

public class AlarmHelper {
	SharedPreferences prefs;

	public static int REQUEST_CODE = 1;

	private Context context;
	private static AlarmHelper aHelper;

	private static SparseArray<PendingIntent> pIntentMap;
	private AlarmManager alarmManager;

	public static AlarmHelper getInstance(Context context) {
		if (null == aHelper)
			aHelper = new AlarmHelper(context);
		// to update the context each time a service helper it's called
		aHelper.setContext(context);
		pIntentMap = new SparseArray<PendingIntent>();

		return aHelper;
	}

	public static AlarmHelper getInstance() {
		if (null != aHelper) {
			return aHelper;
		}
		return null;
	}

	/*
	 * public static AlarmHelper getInstance() { //for Content provider only
	 * return aHelper; }
	 */
	public void setContext(Context context) {
		this.context = context;
	}

	private AlarmHelper(Context mcontext) {
		context = mcontext;
		// create the object
		alarmManager = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		prefs = context.getSharedPreferences("vn.qnamuni.calendar",
				Context.MODE_PRIVATE);
	}

	// -------------------------------------------------------------
	public void addAlarms(Set<Integer> idSet) {
		try {
			String projection[] = { PersonContract.Entry.KEY_ID,
					PersonContract.Entry.KEY_UID, PersonContract.Entry.KEY_DATE,
					PersonContract.Entry.KEY_TIME };
			Cursor c;
			for (int id : idSet) {
				c = context.getContentResolver().query(
						MyContentProvider.CONTENT_URI, projection,
						PersonContract.Entry.KEY_ID + " LIKE ?",
						new String[] { "%" + String.valueOf(id) + "%" }, null);
				c.moveToFirst();
				if (c.getCount() > 0) {
					String date = c.getString(2);
					String time = c.getString(3);
					setAlarm(id, date, time);
				}
			}
		} catch (Exception e) {
			Log.v("Add Alarm Exception", e.getMessage());
		}

	}

	// set an event
	public void setAlarm(int id, String date, String time) {
		try {
			if (null != date && !date.equals("null") && !date.equals("")) {

				PendingIntent pResult = scheduleAlarm(id, new Date(date, time), 0);
				if (null != pResult) {
					pIntentMap.put(id, pResult);
				}
			}
		} catch (Exception e) {
			Log.v("setAlarm 1 Exception", e.getMessage());
		}

	}

	public void setAlarm(int id, String date, String time, String noDayBefore) {
		if (null != date && !date.equals("null") && !date.equals("")) {
			try {
				int num = Integer.parseInt(noDayBefore);
				Log.v("Set no before",  noDayBefore + "");
				if (!noDayBefore.equals("") && !noDayBefore.equals("0")) {
					PendingIntent pResult1 = scheduleAlarm(id, new Date(
							date, time), num);
					if (null != pResult1)
						pIntentMap.put(id, pResult1);
				}
			} catch (Exception e) {
				Log.v("Setalarm", e.getMessage());
			}

		}
	}

	// delete an event
	public boolean stopAlarm(int id) {
		// We cancel alarms that matches with pending intent
		PendingIntent pInt = pIntentMap.get(id);
		if (pInt != null) {
			alarmManager.cancel(pInt);
			Toast.makeText(context, "Alarms stopped", Toast.LENGTH_SHORT)
					.show();
			return true;
		}
		return false;
	}

	// update an event
	public boolean updateAlarm(String event, String time) {
		return false;
	}

	// -------------------------------------------------------------
	// must store every pendingIntent with unique id to recover when necessary
	/*
	 * map(id, index)
	 */
	private PendingIntent scheduleAlarm(int id, Date date, int numDayBefore) {

		GregorianCalendar gc = new GregorianCalendar(
				date.getInfo(Calendar.YEAR), date.getInfo(Calendar.MONTH) - 1,
				date.getInfo(Calendar.DATE) - numDayBefore,
				date.getInfo(Calendar.HOUR), date.getInfo(Calendar.MINUTE),
				date.getInfo(Calendar.SECOND));
		Log.v("date", gc.getTime() + " ");

		// create an Intent and set the class which will execute when Alarm
		// triggers, here we have
		// given AlarmReciever in the Intent, the onRecieve() method of context
		// class will execute when
		// alarm triggers and
		// we will write the code to send SMS inside onRecieve() method pf

		// long time = new GregorianCalendar().getTimeInMillis() + 10 * 1000;
		Intent intent = new Intent(context, AlarmReciever.class);
		intent.putExtra(PersonContract.Entry.KEY_ID, id);
		intent.putExtra("mode", 1);

		Log.v("scheule", id + "");
		// different request code
		// auto update
		PendingIntent pIntent = PendingIntent.getBroadcast(context,
				REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

		// set the alarm for particular time
		alarmManager
				.set(AlarmManager.RTC_WAKEUP, gc.getTimeInMillis(), pIntent);
//		Toast.makeText(context, "id = " + id, Toast.LENGTH_LONG).show();

		return pIntent;
	}
}
